package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.cart.client.CartInfoFeignClient;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: 李旭
 * @create: 2021-09-06 15:33
 *
 *   加入购物车
 *
 *     Controller 同步
 *     RestController 异步  Result对象  JSON格式字符串
 **/
@Controller
public class CartInfoController {


    @Autowired
    private CartInfoFeignClient cartInfoFeignClient;
    //加入购物车
    @GetMapping("/addCart.html")
    public String addCart(Long skuId, Integer skuNum,
                          RedirectAttributes redirectAttributes
                           , HttpServletRequest request){
        //获取用户ID
 /*       String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);*/
        System.out.println("加入购物车成功");
        try {
            cartInfoFeignClient.addCart(skuId, skuNum);//业务入参  库存Id  数量
        } catch (Exception e) {
            //e.printStackTrace();
            //重定向
            return "redirect:http://www.gmall.com";
        }
        redirectAttributes.addAttribute("pid",skuId);
        redirectAttributes.addAttribute("rcd",skuNum);
        //重定向
        return "redirect:http://cart.gmall.com/toCart.html";
    }
    //商品已成功加入购物车！
    @GetMapping("/toCart.html")
    public String toCart(Model model,Long pid,Integer rcd){
        CartInfo cartInfo = cartInfoFeignClient.findCartInfo(pid);
        //设置本次添加的数量
        cartInfo.setSkuNum(rcd);
        model.addAttribute("cartInfo",cartInfo);
        //加入购物车商品成功
        return "cart/addCart";
    }
    //去购物车页面
    @GetMapping("/cart.html")
    public String cart(){
        return "cart/index";
    }
}
